package cn.sxgan.gen.interceptor;

import cn.sxgan.gen.config.DynamicDataSourceContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class DataSourceHeaderInterceptor implements HandlerInterceptor {
    
    // 请求头名称常量
    public static final String DATA_SOURCE_HEADER = "Data-Source";
    
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {
        // 从请求头获取数据源标识
        String dataSourceKey = request.getHeader(DATA_SOURCE_HEADER);
        
        if (dataSourceKey != null && !dataSourceKey.isBlank()) {
            // 设置当前线程数据源
            DynamicDataSourceContextHolder.setDataSourceKey(dataSourceKey);
            log.info("[{}] 设置数据源: {}", request.getRequestURI(), dataSourceKey);
        }
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request,
                              HttpServletResponse response,
                              Object handler,
                              Exception ex) {
        // 请求完成后清除线程上下文
        // DynamicDataSourceContextHolder.clearDataSourceKey();
        
        // 日志记录
        // System.out.println("[" + request.getRequestURI() + "] 清除数据源上下文");
    }
}